package com.ytq.pratice.java.list;

/**
 * @author yuantongqin
 * @date 2018/10/10 上午11:02
 */
public class MyLinkedList {

    /**
     * 插入头结点
     */
    public static void insertHead(ListNode head, ListNode newHead) {
        ListNode old = head;
        head = newHead;
        head.next = old;
    }


    /**
     * 插入尾节点
     */
    public static void insertTail(ListNode tail, ListNode newTail) {
        ListNode old = tail;
        tail = newTail;
        old.next = tail;
        tail.next = null;

    }

    /**
     * 插入中间节点
     */
    public static void insert(ListNode A, ListNode B) {
        ListNode next = A.next;
        A.next = B;
        B.next = next;
    }


    /**
     * 遍历
     */
    public static void traverse(ListNode head) {
        while (head != null) {
            System.out.println(head.value + "==value");
            head = head.next;
        }
    }

    /**
     * 查找
     */
    public static int find(ListNode head, String value) {
        int index = -1;
        int count = 0;
        while (head != null) {
            if (!"".equals(value) && value.equals(head.value)) {
                return count;
            }
            count++;
            head = head.next;
        }
        return index;
    }

    /**
     * 删除分为两种情况，删除尾节点和中间节点
     */
    public static void delete(ListNode head, ListNode node) {
        //1、删除中间节点，将删除节点的下一个节点值替换当前删除节点
        if (node != null && node.next != null) {
            ListNode next = node.next;
            node.value = next.value;
            node.next = next.next;
            next = null;

        }

        //删除的是尾节点，就需要找到他的上一个节点然后把next=null
        if(node.next == null){
            while (head != null) {
                if (head.next != null && head.next == node) {
                    head.next = null;
                    break;
                }
                head = head.next;
            }
        }

    }

    public static void main(String[] args) {

        ListNode node1 = new ListNode("1");
        ListNode node2 = new ListNode("2");
        ListNode node3 = new ListNode("3");
        node1.next= node2;
        node2.next = node3;
        node3.next = null;
        traverse(node1);
        ListNode newhead = new ListNode("4");
        insertHead(node1,newhead);
        insertTail(node3,new ListNode("5"));
        insert(node2,new ListNode("6"));
        traverse(newhead);

        delete(newhead,node2);
        traverse(newhead);



    }

}
